package servlet;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import connection.DbConnection;

import model.PollUserImpl;
import bean.PollUser;
public class loginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8767999581281709013L;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost (request, response);
	}
	
	public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("GBK");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		// Create user
		PollUser user = new PollUser();
		user.setUsername(username);
		user.setPassword(password);
		
		// Check if user exists
		if (!PollUserImpl.checkUserNameOnly(user)) {
			request.getSession().setAttribute("UsernameIncorrect", "ttrue");
			response.sendRedirect("login.jsp");
			//RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
			//rd.forward(request, response);
	
		} else {
			request.getSession().setAttribute("UsernameIncorrect", "ffalse");
		
			// Check user + password combination
			if (!PollUserImpl.checkuser(user)) {
				request.getSession().setAttribute("PasswordIncorrect", "ttrue");
				response.sendRedirect("login.jsp");

			} else {
				request.getSession().setAttribute("PasswordIncorrect", "ffalse");
				
				// Set all user bean attributes
				PollUserImpl.setUserAttributes(user);
				
				// Set session variables for all
				//request.getSession().setAttribute("UserBean", user);
				request.getSession().setAttribute("username", user.getUsername());
				request.getSession().setAttribute("password", user.getPassword());
				request.getSession().setAttribute("email", user.getEmail());
				request.getSession().setAttribute("accessibility", user.getAccessibility());
				request.getSession().setAttribute("createDate", user.getCreateDate());
				request.getSession().setAttribute("generic", user.getGenericUser());
				request.getSession().setAttribute("expireDate", user.getExpireDate());
				request.getSession().setAttribute("fname", user.getFirstname());
				request.getSession().setAttribute("lname", user.getLastname());
				
				// Send page
				response.sendRedirect("success.jsp");
				

			}
		}
	}
}
